<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<div th:replace="admin/module/macros :: head(${activity != null ? '编辑活动' : '新增活动'})"></div>
<body class="app sidebar-mini rtl">
    <div th:replace="admin/module/macros :: header"></div>
    <div th:replace="admin/module/macros :: sidebar"></div>
    <main class="app-content">
        <div class="app-title">
            <div>
                <h1><i class="fa fa-edit"></i> <span th:text="${activity != null ? '编辑活动' : '新增活动'}"></span></h1>
                <p>填写活动信息</p>
            </div>
            <ul class="app-breadcrumb breadcrumb">
                <li class="breadcrumb-item"><i class="fa fa-home fa-lg"></i></li>
                <li class="breadcrumb-item"><a href="/admin/activities">活动管理</a></li>
                <li class="breadcrumb-item"><span th:text="${activity != null ? '编辑活动' : '新增活动'}"></span></li>
            </ul>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="tile">
                    <div class="row">
                        <div class="col-lg-12">
                            <form id="activityForm">
                                <input type="hidden" name="activityId" th:value="${activity != null ? activity.activityId : ''}">
                                
                                <div class="form-group">
                                    <label for="activityName">活动名称</label>
                                    <input class="form-control" id="activityName" name="activityName" type="text" 
                                           placeholder="请输入活动名称" th:value="${activity != null ? activity.activityName : ''}" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="activityAddress">活动地点</label>
                                    <input class="form-control" id="activityAddress" name="activityAddress" type="text" 
                                           placeholder="请输入活动地点" th:value="${activity != null ? activity.activityAddress : ''}">
                                </div>
                                
                                <div class="form-group">
                                    <label>活动封面</label>
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" id="coverImage" accept="image/*">
                                        <label class="custom-file-label" for="coverImage">选择图片</label>
                                    </div>
                                    <input type="hidden" name="coverImage" id="coverImagePath" th:value="${activity != null ? activity.coverImage : ''}">
                                    <div class="mt-3" id="coverPreview">
                                        <img th:if="${activity != null && activity.coverImage != null}" th:src="${activity.coverImage}" 
                                             style="max-width: 100%; max-height: 300px;">
                                    </div>
                                </div>
                                
                                <div class="form-group">
                                    <label for="startTime">开始时间</label>
                                    <input class="form-control" id="startTime" name="startTime" type="datetime-local" 
                                           th:value="${activity != null && activity.startTime != null ? #dates.format(activity.startTime, 'yyyy-MM-dd''T''HH:mm') : ''}" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="endTime">结束时间</label>
                                    <input class="form-control" id="endTime" name="endTime" type="datetime-local" 
                                           th:value="${activity != null && activity.endTime != null ? #dates.format(activity.endTime, 'yyyy-MM-dd''T''HH:mm') : ''}">
                                </div>
                                
                                <div class="form-group">
                                    <label for="activityDescription">活动描述</label>
                                    <textarea class="form-control" id="activityDescription" name="activityDescription" rows="10" 
                                              placeholder="请输入活动详细描述" th:text="${activity != null ? activity.activityDescription : ''}"></textarea>
                                </div>
                                
                                <div class="tile-footer">
                                    <button class="btn btn-primary" type="button" id="submitBtn">
                                        <i class="fa fa-fw fa-lg fa-check-circle"></i>保存
                                    </button>
                                    <a class="btn btn-secondary" href="/admin/activities">
                                        <i class="fa fa-fw fa-lg fa-times-circle"></i>取消
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
    <div th:replace="admin/module/macros :: copyright"></div>
    <div th:replace="admin/module/macros :: bootstrap"></div>
    
    <!-- 引入富文本编辑器 -->
    <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
    
    <script>
        $(document).ready(function() {
            // 初始化富文本编辑器
            tinymce.init({
                selector: '#activityDescription',
                height: 400,
                plugins: 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table paste code help wordcount',
                toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help',
                menubar: false
            });
            
            // 处理封面图片上传
            $('#coverImage').change(function() {
                var file = this.files[0];
                if (file) {
                    var formData = new FormData();
                    formData.append('file', file);
                    
                    $.ajax({
                        url: '/admin/activities/upload/cover',
                        type: 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function(result) {
                            if (result.success) {
                                // 上传成功，显示预览并保存路径
                                $('#coverImagePath').val(result.data);
                                $('#coverPreview').html('<img src="' + result.data + '" style="max-width: 100%; max-height: 300px;">');
                                $('.custom-file-label').text(file.name);
                            } else {
                                // 上传失败
                                swal("上传失败", result.msg, "error");
                            }
                        },
                        error: function() {
                            swal("上传失败", "请求发生错误，请重试", "error");
                        }
                    });
                }
            });
            
            // 表单提交
            $('#submitBtn').click(function() {
                // 获取富文本编辑器的内容
                var description = tinymce.get('activityDescription').getContent();
                
                // 表单验证
                if (!$('#activityName').val()) {
                    swal("验证失败", "请填写活动名称", "error");
                    return;
                }
                
                if (!$('#startTime').val()) {
                    swal("验证失败", "请设置活动开始时间", "error");
                    return;
                }
                
                // 准备提交的数据
                var formData = {
                    activityId: $('input[name="activityId"]').val(),
                    activityName: $('#activityName').val(),
                    activityAddress: $('#activityAddress').val(),
                    coverImage: $('#coverImagePath').val(),
                    activityDescription: description,
                    startTime: $('#startTime').val(),
                    endTime: $('#endTime').val() || null
                };
                
                // 发送AJAX请求保存活动
                $.ajax({
                    url: '/admin/activities/save',
                    type: 'POST',
                    data: formData,
                    success: function(result) {
                        if (result.success) {
                            // 保存成功
                            swal({
                                title: "保存成功",
                                text: result.msg,
                                icon: "success",
                                button: "确定"
                            }).then(() => {
                                window.location.href = '/admin/activities';
                            });
                        } else {
                            // 保存失败
                            swal("保存失败", result.msg, "error");
                        }
                    },
                    error: function() {
                        swal("操作失败", "请求发生错误，请重试", "error");
                    }
                });
            });
        });
    </script>
</body>
</html>
